package com.tms.drivermanagement.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.core.utils.uuid.UUID;

import com.tms.drivermanagement.service.FileUploadService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.keyid}")
    private String keyid;
    @Value("${aliyun.keysecret}")
    private String keysecret;
    @Value("${aliyun.bucketname}")
    private String bucketname;

    @Override
    public String fileUpload(MultipartFile file) {
        String url="";
        // 1.创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);

        try {
            // 2.获取文件流
            InputStream inputStream = file.getInputStream();
            //获取文件名
            String filename = file.getOriginalFilename();
            //随机生成一个字符串
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid + filename;
            //存储路径  年月日做间隔
            String time = new DateTime().toString("yyyy/MM/dd");
            filename = time + "/" + filename;
            // 3.上传
            PutObjectResult result = ossClient.putObject(bucketname, filename, inputStream);
            // 5.获取图片上传后的文件路径
            url="https://"+bucketname+"."+endpoint+"/"+filename;
            ossClient.shutdown();

        } catch (Exception oe) {
            System.out.println("上传发生异常");

        } finally {
            // 4.关闭
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}
